package edu.sctu.yueding.activitys;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.mobsandgeeks.saripaar.Rule;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.annotation.ConfirmPassword;
import com.mobsandgeeks.saripaar.annotation.Password;
import com.mobsandgeeks.saripaar.annotation.Required;
import com.mobsandgeeks.saripaar.annotation.TextRule;

import java.util.HashMap;

import edu.sctu.yueding.R;
import edu.sctu.yueding.bean.JsonBaseBeen;
import edu.sctu.yueding.config.CacheConfig;
import edu.sctu.yueding.config.URLConfig;
import edu.sctu.yueding.utils.JumpUtils;
import edu.sctu.yueding.utils.ProgressUtil;
import edu.sctu.yueding.utils.httputils.GetVolleyHttp;
import edu.sctu.yueding.utils.httputils.SharePreference;
import edu.sctu.yueding.view.TimeButton;

/**
 * Created by fll on 2016/8/3.
 */
public class ResetPasswordActivity extends BaseActivity implements View.OnClickListener,Validator.ValidationListener {

    private ImageView mRegisterBackButton;

    @Required(order = 1)
    @TextRule(order = 2, minLength = 11,maxLength = 11,message = "请输入正确的电话号码！")
    private EditText mRegisterPhone;

    @Required(order = 3,message = "必填选项！")
    private EditText mRegisterCode;

    @Required(order = 4,message = "必填选项！")
    @Password(order = 5)
    private EditText mFirstPasswoerd;

    @Required(order = 6,message = "必填选项！")
    @ConfirmPassword(order = 7,message = "两次密码不一致！")
    private EditText mRegisterPassword;

    private TimeButton mGetCode;

    private String username;
    private String password;
    private String oPassword;
    private String code;
    private Button buttonRegister;

    private Validator validator;

    private ProgressUtil progressUtil;
    private String show = null;
    private ProgressDialog progressDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.myinfo_reset_password);
        initView();
        initSystemBar(this, R.color.hometext);


    }

    private void initView() {


        validator = new Validator(this);

        mRegisterBackButton = (ImageView) findViewById(R.id.myinfo_reset_password_button_back);

        mRegisterPhone = (EditText) findViewById(R.id.myinfo_reset_password_edittext_number);
        mRegisterCode = (EditText) findViewById(R.id.myinfo_reset_password_edittext_identy);


        mRegisterPassword = (EditText) findViewById(R.id.myinfo_reset_password_edittext_password);
        mFirstPasswoerd = (EditText) findViewById(R.id.myinfo_reset_password_password);

        progressUtil = ProgressUtil.getInstance(ResetPasswordActivity.this, show);

        buttonRegister = (Button) findViewById(R.id.myinfo_reset_password_button_register);
        mGetCode = (TimeButton) findViewById(R.id.myinfo_reset_password_button_get_identy);
        mGetCode.setTextBefore("点击获取验证码");

        setEvent();

    }

    private void setEvent() {

        mGetCode.setOnClickListener(this);
        buttonRegister.setOnClickListener(this);
        mRegisterBackButton.setOnClickListener(this);
        validator.setValidationListener(this);
    }


    @Override
    public void onClick(View view) {

        switch (view.getId()) {

            case R.id.myinfo_reset_password_button_get_identy:

                getValidationCode();

                break;

            case R.id.myinfo_reset_password_button_register:

                validator.validate();

                break;

            case R.id.myinfo_reset_password_button_back:
                finish();
                break;
        }

    }

    private void register() {


        buttonRegister.setClickable(false);
        buttonRegister.setText(null);


        username = mRegisterPhone.getText().toString();
        code = mRegisterCode.getText().toString();

        oPassword = mFirstPasswoerd.getText().toString();
        password = mRegisterPassword.getText().toString();


        HashMap<String, String> map = new HashMap<String, String>();

        map.put("login", username);
        map.put("newPassword", password);
        map.put("code", code);

        GetVolleyHttp.getInstance(ResetPasswordActivity.this).getStringPOSTJsonData(URLConfig.RESET_PASSWORD, map,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {


                        JsonBaseBeen<String> jsonBaseBeen = JSON.parseObject(response, new TypeReference<JsonBaseBeen<String>>() {
                        }.getType());

                        Log.e("5555", response);
                        progressUtil.dismiss(progressDialog);

                        if (jsonBaseBeen.getMeta().code == 200) {

                            Toast.makeText(ResetPasswordActivity.this, "修改成功,请登录！", Toast.LENGTH_SHORT).show();
                            finish();
                            SharePreference.getInstance(ResetPasswordActivity.this).setCache(CacheConfig.CACHE_USER_NAME,username);
                            JumpUtils.jumpActivity(ResetPasswordActivity.this, LoginActivity.class);

                        } else if (jsonBaseBeen.getMeta().code == 40000900) {
                            buttonRegister.setClickable(true);
//                            buttonRegister.setText("注册");
                            Toast.makeText(ResetPasswordActivity.this, "该用户不存在", Toast.LENGTH_SHORT).show();

                        } else if (jsonBaseBeen.getMeta().code == 406) {
                            buttonRegister.setClickable(true);
//                            buttonRegister.setText("注册");
                            Toast.makeText(ResetPasswordActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                        error.printStackTrace();
                        buttonRegister.setClickable(true);
                        progressUtil.dismiss(progressDialog);
                        Toast.makeText(ResetPasswordActivity.this, "网络出了点问题！！", Toast.LENGTH_LONG).show();

                    }
                });
    }


    private void getValidationCode() {


        username = mRegisterPhone.getText().toString();

        mGetCode.setTextAfter("秒后重新获取");
        mGetCode.setClick();

        GetVolleyHttp.getInstance(ResetPasswordActivity.this).getStringGETJsonData(URLConfig.getSmsVerification(username), new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {

                Log.e("12", response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }, "");
    }

    @Override
    public void onValidationSucceeded() {

        progressDialog = progressUtil.getProgressDialog(ProgressDialog.STYLE_HORIZONTAL, true);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                register();
            }
        },1000);


    }

    @Override
    public void onValidationFailed(View failedView, Rule<?> failedRule) {

        String message = failedRule.getFailureMessage();

        if (failedView instanceof EditText) {
            failedView.requestFocus();
            ((EditText) failedView).setError(message);
        } else {
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        }
    }


}
